<template>
  <div id="app" @click="click(1)" class="appd">
    <!-- <div class="n_body1">
      <div id="loader-wrapper">
        <div id="loader"></div>
        <div class="loader-section section-left" ></div>
        <div class="loader-section section-right"></div>
      </div>
    </div> -->
    <v-touch v-on:swipeleft="swiperleft"  v-on:swiperight="swiperright" class="wrapper">
      <router-view v-if="isRouterAlive" class="n_body2">  </router-view>
    </v-touch>
    <!-- <Nav></Nav> -->
  </div>
</template>

<script>
export default {
  name: 'App',
  data() {
    return{
      isRouterAlive: true,
      timer:'',
      sizenum:0,//时间计数
      repnum:3,//重复时间秒
      repeatnum:0,//失败访问次数
      timeGetData:'',//计时定时器
      parsedData:{},
      timeNum:0,
      typenum:3,//重复时间秒
      typerepeatnum:0,//失败访问次数
      typesizenum:0,//时间计数
      timeGetType:'',//计时定时器
    }
  },
  provide () {
    return {
      reload: this.reload,
    }
  },
  created() {
    window.localStorage.removeItem('当前访问路径')
    const url = window.location.href;
    this.getoverview2(url)
    this.click(1); 
    this.getTypename()
  },
  mounted() {
    // 缩放适配
    this.renderDisplay();
    (window.onresize = () => {
      this.renderDisplay();
    })
  },
  methods: {
    // 提取路径名
    extractPathname(url) {
      const pathnameMatch = url.match(/#\//g);
      if (pathnameMatch) {
        const startOfPath = url.indexOf('#/') + 2; // 跳过 '#/' 
        const endOfPath = url.indexOf('?', startOfPath); // 查找 '?' 以确定路径结束的位置
        return url.substring(startOfPath, endOfPath);
      }
      return null;
    },
    // 提取查询参数
    extractQueryParams(url) {
      const queryParams = {};
      const queryStart = url.indexOf('?');
      if (queryStart !== -1) {
        const queryPart = url.slice(queryStart + 1);
        const params = queryPart.split('&').map(param => param.split('='));
        params.forEach(([key, value]) => {
          queryParams[key] = decodeURIComponent(value);
        });
      }
      return queryParams;
    },
    splitCodeValue(codeValue) {
      const values = codeValue.split('-');
      const codeObj = {
        code: values[0],
        uid: values[1],
        type: values[2],
        addr: values[3]
      };
      return codeObj;
    },
    //判断链接中的特殊编码
    getoverview2(url){ //http://10.168.0.13/#/overview2?code=123456-00000000000001-17-1
      // const url = "http://localhost:8080/#/overview2?code=123456-00000000000001-17-1";  通过特殊编码直接访问设备内页
      // const url = "http://localhost:8080/#/?code=123456"; 通过特殊编码访问首页
      const path = this.extractPathname(url); // 输出: overview2
      const params = this.extractQueryParams(url); // 内页访问输出: {"code": "123456-00000000000001-17-1"}
      console.log('Path:', path); 
      console.log('Updated Params:', params);  // 首页访问输出:{"code": "123456"}
      localStorage.setItem("当前访问路径", path)
      if(params.code == undefined){//无特殊编码访问，跳出判断正常访问
        console.log('原地址')
        localStorage.setItem("_username", '');
        localStorage.setItem("当前用户权限","游客");//清空之前的登录状态
        localStorage.setItem("cookieName", 'cookie');
        localStorage.setItem("_token", '0');
        console.log('刷新页面退出登录状态')
        setTimeout(() => {
          this.getusersize()
        }, 500)
        
        this.synctime()
        this.getsystem()   
        this.$router.push({ path:'/' }) 
        return false
      }else{
        //监测到通过特殊编码进入
        const codeValues = this.splitCodeValue(params.code); // 内页访问输出: { code: "123456", uid: "00000000000001", type: "17", addr: "1" }
        console.log(codeValues) // 首页访问输出: { code: "123456", uid:undefined, type: undefined, addr: undefined }
        this.$http.post(this.$baseUrl,{ // 获取账户列表  筛选特殊编码是否存在，并属于哪一账号
                "getuserlist":"",
        }).then((res)=>{
          if(res.data.result == 'ok'){
            var ss = 0 
            for(var i = 0; i < res.data.getuserlist.length; i++){
              if(codeValues.code == res.data.getuserlist[i].encode){
                ss = 1
                this.$message({
                  message: '通道建立成功',
                  type: 'success',
                  duration: 1000
                });
                localStorage.setItem("_username", res.data.getuserlist[i].name);
                // this.$store.commit("changeUserName", res.data.getuserlist[i].name);
                if(res.data.getuserlist[i].limit == 'all'){
                  localStorage.setItem("当前用户权限",'高级管理员')
                }else if(res.data.getuserlist[i].limit == 'administrators'){
                  localStorage.setItem("当前用户权限",'普通管理员')
                }else if(res.data.getuserlist[i].limit == 'tourist'){
                  localStorage.setItem("当前用户权限",'普通用户')
                }else if(res.data.getuserlist[i].limit == 'thirdparty'){
                  localStorage.setItem("当前用户权限",'第三方用户')
                }
              }
            }
            if(ss == 0){ // 特殊编码无效
              this.$message({
                message: '特殊编码无效',
                type: 'error',
                duration: 1000
              });
              localStorage.setItem("_username", '');
              localStorage.setItem("当前用户权限","游客");
              localStorage.setItem("cookieName", 'cookie');
              localStorage.setItem("_token", '0');
              console.log('特殊编码无效清空登录状态')
            }else{ // 监测到特殊编码有效
              //用户权限赋值
              localStorage.setItem("_token", codeValues.code);
              localStorage.setItem("cookieName", 'encode');
              // 内页访问逻辑
              if(codeValues.uid != undefined){
                var arr = {
                  name:'',
                  uid:codeValues.uid,
                  type:Number(codeValues.type),
                  addr:Number(codeValues.addr)
                }
                localStorage.setItem('6.0展示设备卡片', JSON.stringify(arr))
                this.$router.push({ path:'/' }) 
                setTimeout(()=>{
                  this.$router.push({ path:'/overview2' }) 
                },10)
              }else{
                //首页特殊编码访问
                this.$router.push({ path:'/' }) 
                
              }
            }
          }
        })
        
      }
      
    },
    // 获取账号数量
    getusersize(){
      // 接口访问失败逻辑循环：3秒无返回认定接口失败，并重新访问接口，以上情况下接口循环访问达到5次后，接口循环重新访问时间延长到15秒一次，接口访问成功后该方法自动重置
      var size;
      this.$nextTick(() => {
        this.timeGetData = setInterval(() => {
          if(this.sizenum >= this.repnum){ //达到3000ms延迟等待结果未返回
            clearInterval(this.timeGetData); //清除定时器
            this.timeGetData = null; //清除定时器
            this.sizenum = 0 //时间计数重置
            if(size == undefined){ //接口没有拿到返回
                if(this.$router.currentRoute.path != localStorage.getItem("当前主页")){
                  this.$router.push({'path':'/'});
                }
              this.$message({
                message: '服务器访问失败',
                type: 'error',
                duration: 1000
              });
              this.repeatnum++ //失败访问次数累计
              if(this.repeatnum >= 4){ // 第五次接口访问失败后，接口访问频率改成15秒（12+3）
                this.repnum = 15 //重复时间频率增大
                this.getusersize()
              }else{
                this.getusersize() //重新访问接口
              }
            }else{
              this.repeatnum = 0 //失败访问次数重置
            }
          }else{
            this.sizenum++; //时间累计
          }
        }, 1000); 
      })
      // -----------------------------
      var params = {
       'getusersize':""
      }
      this.$http.post(this.$baseUrl, params).then((res) => {
        // 接口失败重复逻辑相关
        size = res.data.getusersize;
        this.repnum = 3 //重复时间频率变回3000ms
        // ----------------------
        if(res.data.getusersize == 0){
          localStorage.setItem("当前用户权限",'首次进入')
          localStorage.setItem("_token", "0");
          localStorage.setItem("_username", "");
        }else{
          var Grade = localStorage.getItem("当前用户权限")
          if(Grade != '高级管理员' && Grade != '普通管理员' && Grade != '普通用户' && Grade != '第三方用户'){
            console.log('权限等级'+localStorage.getItem("当前用户权限"))
            localStorage.setItem("当前用户权限","游客")
          }
        }
      })
    },
    getTypename(){
      // 接口访问失败逻辑循环：3秒无返回认定接口失败，并重新访问接口，以上情况下接口循环访问达到5次后，接口循环重新访问时间延长到15秒一次，接口访问成功后该方法自动重置
      var data; //undefined
      this.$nextTick(() => {
        this.timeGetType = setInterval(() => {
          if(this.typesizenum >= this.typenum){ //达到3000ms延迟等待结果未返回  定时器1秒一判断，等到累计时间到达3秒或15秒后就进入逻辑，先清除定时器，  
            clearInterval(this.timeGetType); //如果判断接收到的内容为空或失败，则继续请求此方法重新开始定时器，期间累计访问失败的次数，当次数达到5次后，将等待时间增加到15秒
            this.timeGetType = null; //清除定时器
            this.typesizenum = 0 //时间计数重置
            if(data == undefined){ //接口没有拿到返回
              this.typerepeatnum++ //失败访问次数累计
              if(this.typerepeatnum >= 4){ // 第五次接口访问失败后，接口访问频率改成15秒（12+3）
                this.typenum = 15 //重复时间频率增大
                this.getTypename() //此时定时器已销毁，需要重新访问方法开启定时器
              }else{
                this.getTypename() //此时定时器已销毁，需要重新访问方法开启定时器
              }
            }else{ //接口拿到返回 停止定时器请求
              this.typerepeatnum = 0 //失败访问次数重置
            }
          }else{
            this.typesizenum++; //时间累计
          }
        }, 1000); 
      })
      var params = {
       'gettypename':""
      }
      this.$http.post(this.$baseUrl, params).then((res) => {
        // 接口失败重复逻辑相关
        data = res.data.typename;
        this.typenum = 3 //重复时间频率变回3000ms
        var arr = []
        for(var i = 0; i < res.data.typename.length; i++){
          if(res.data.typename[i].typename != '未知设备'){
            arr.push(res.data.typename[i])
          }
        }
        localStorage.setItem('全部设备类型',JSON.stringify(arr))   
      })
    },
    swiperleft: function () {  //左划切换到goods页
      if(localStorage.getItem("当前主页") == '/Humi'){
        this.$router.push({'path':'/'});
      }else{
        return false
      }
    },
    swiperright: function () { //右滑切换到detail页
      if(localStorage.getItem("当前主页") == '/Humi'){
        this.$router.push({'path':'/Humi'});
      }else{
        return false
      }
    },
    // 时间同步
    synctime(){
      // localStorage.setItem("systemTime", res.data.ntime);
      let time =  Date.parse(new Date())/1000;
      var paramsTime = {
        "settime":time,//时间戳，单位秒
      }
      this.$http.post(this.$baseUrl, paramsTime).then((res) => {
          if(res.data.result !== 'ok'){
          }else{
          }
      }); 
  },
  getsystem(){
            var web = "V0.0.38" //前端版本号
      if(localStorage.getItem('versionWeb') == undefined){
        localStorage.setItem("versionWeb", web);
      }else{
        if(localStorage.getItem('versionWeb') !=  web){
          localStorage.setItem("versionWeb", web);
          window.localStorage.removeItem('menuDataJson')
          window.localStorage.removeItem('time')
          window.localStorage.removeItem('video')
          window.localStorage.removeItem('当前主页')
          window.localStorage.removeItem('warnData')
          window.localStorage.removeItem('stime')
          window.localStorage.removeItem('navbar')
          window.localStorage.removeItem('map')
          window.localStorage.removeItem('loglevel:webpack-dev-server')
          window.localStorage.removeItem('videos')
          window.localStorage.removeItem('moveArr')
          window.localStorage.removeItem('doors')
          window.localStorage.removeItem('当前用户权限')
          window.localStorage.removeItem('cookieName')
          window.localStorage.removeItem('phone')
          // window.localStorage.removeItem('tempCurve')
          // localStorage.clear();
          location.reload();
        }
      }

  },
    // 页面更新方法
    reload () {
      this.isRouterAlive = false;
      this.$nextTick ( ()=> {
        this.isRouterAlive = true
      })
    },

    // 

    click(e) {
      clearInterval(this.timer);
      this.timer = null;
      this.timeNum = e
      this.timer = setInterval(()=>{
        // console.log(this.timeNum*10+'秒')
          this.timeNum++;
          if(this.timeNum > 180){
            if(localStorage.getItem("cookieName") == 'encode'){
            }else{
              localStorage.setItem("_token", "0");
              localStorage.setItem("_username", "");
              localStorage.setItem("当前用户权限","游客");
              console.log(this.timeNum*10+'秒没有操作退出登录')
              this.$router.push({
                path: "/",
              });
              this.$notify.info({
                  title: '账号已失效',
                  duration: 1500
              });
            }
            this.timeNum = 0
            clearInterval(this.timer)
            this.timer = null;
          }
      }, 10000);
    },
  },
   // 清除定时器
   beforeDestroy() {
      // 停止循环接口
      clearInterval(this.timer);
      this.timer = null;
  }
}
</script>
<style scoped>
.chromeframe {
      margin: 0.2em 0;
      background: #ccc;
      color: #000;
      padding: 0.2em 0;
    }

    #loader-wrapper {
      position: fixed;
      top: 0;
      left: 0;
      width: 100%;
      height: 100%;
      z-index: 999999;
    }

    #loader {
      display: block;
      position: relative;
      left: 50%;
      top: 50%;
      width: 150px;
      height: 150px;
      margin: -75px 0 0 -75px;
      border-radius: 50%;
      border: 3px solid transparent;
      /* COLOR 1 */
      border-top-color: #FFF;
      -webkit-animation: spin 2s linear infinite;
      /* Chrome, Opera 15+, Safari 5+ */
      -ms-animation: spin 2s linear infinite;
      /* Chrome, Opera 15+, Safari 5+ */
      -moz-animation: spin 2s linear infinite;
      /* Chrome, Opera 15+, Safari 5+ */
      -o-animation: spin 2s linear infinite;
      /* Chrome, Opera 15+, Safari 5+ */
      animation: spin 2s linear infinite;
      /* Chrome, Firefox 16+, IE 10+, Opera */
      z-index: 1001;
    }

    #loader:before {
      content: "";
      position: absolute;
      top: 5px;
      left: 5px;
      right: 5px;
      bottom: 5px;
      border-radius: 50%;
      border: 3px solid transparent;
      /* COLOR 2 */
      border-top-color: #FFF;
      -webkit-animation: spin 3s linear infinite;
      /* Chrome, Opera 15+, Safari 5+ */
      -moz-animation: spin 3s linear infinite;
      /* Chrome, Opera 15+, Safari 5+ */
      -o-animation: spin 3s linear infinite;
      /* Chrome, Opera 15+, Safari 5+ */
      -ms-animation: spin 3s linear infinite;
      /* Chrome, Opera 15+, Safari 5+ */
      animation: spin 3s linear infinite;
      /* Chrome, Firefox 16+, IE 10+, Opera */
    }

    #loader:after {
      content: "";
      position: absolute;
      top: 15px;
      left: 15px;
      right: 15px;
      bottom: 15px;
      border-radius: 50%;
      border: 3px solid transparent;
      border-top-color: #FFF;
      /* COLOR 3 */
      -moz-animation: spin 1.5s linear infinite;
      /* Chrome, Opera 15+, Safari 5+ */
      -o-animation: spin 1.5s linear infinite;
      /* Chrome, Opera 15+, Safari 5+ */
      -ms-animation: spin 1.5s linear infinite;
      /* Chrome, Opera 15+, Safari 5+ */
      -webkit-animation: spin 1.5s linear infinite;
      /* Chrome, Opera 15+, Safari 5+ */
      animation: spin 1.5s linear infinite;
      /* Chrome, Firefox 16+, IE 10+, Opera */
    }


    @-webkit-keyframes spin {
      0% {
        -webkit-transform: rotate(0deg);
        /* Chrome, Opera 15+, Safari 3.1+ */
        -ms-transform: rotate(0deg);
        /* IE 9 */
        transform: rotate(0deg);
        /* Firefox 16+, IE 10+, Opera */
      }
      100% {
        -webkit-transform: rotate(360deg);
        /* Chrome, Opera 15+, Safari 3.1+ */
        -ms-transform: rotate(360deg);
        /* IE 9 */
        transform: rotate(360deg);
        /* Firefox 16+, IE 10+, Opera */
      }
    }

    @keyframes spin {
      0% {
        -webkit-transform: rotate(0deg);
        /* Chrome, Opera 15+, Safari 3.1+ */
        -ms-transform: rotate(0deg);
        /* IE 9 */
        transform: rotate(0deg);
        /* Firefox 16+, IE 10+, Opera */
      }
      100% {
        -webkit-transform: rotate(360deg);
        /* Chrome, Opera 15+, Safari 3.1+ */
        -ms-transform: rotate(360deg);
        /* IE 9 */
        transform: rotate(360deg);
        /* Firefox 16+, IE 10+, Opera */
      }
    }


    #loader-wrapper .loader-section {
      position: fixed;
      top: 0;
      width: 51%;
      height: 100%;
      background: #090d15;
      /* Old browsers */
      z-index: 1000;
      -webkit-transform: translateX(0);
      /* Chrome, Opera 15+, Safari 3.1+ */
      -ms-transform: translateX(0);
      /* IE 9 */
      transform: translateX(0);
      /* Firefox 16+, IE 10+, Opera */
    }

    #loader-wrapper .loader-section.section-left {
      left: 0;
    }

    #loader-wrapper .loader-section.section-right {
      right: 0;
    }

    /* Loaded */

    .loaded #loader-wrapper .loader-section.section-left {
      -webkit-transform: translateX(-100%);
      /* Chrome, Opera 15+, Safari 3.1+ */
      -ms-transform: translateX(-100%);
      /* IE 9 */
      transform: translateX(-100%);
      /* Firefox 16+, IE 10+, Opera */
      -webkit-transition: all 0.7s 0.3s cubic-bezier(0.645, 0.045, 0.355, 1.000);
      transition: all 0.7s 0.3s cubic-bezier(0.645, 0.045, 0.355, 1.000);
    }

    .loaded #loader-wrapper .loader-section.section-right {
      -webkit-transform: translateX(100%);
      /* Chrome, Opera 15+, Safari 3.1+ */
      -ms-transform: translateX(100%);
      /* IE 9 */
      transform: translateX(100%);
      /* Firefox 16+, IE 10+, Opera */
      -webkit-transition: all 0.7s 0.3s cubic-bezier(0.645, 0.045, 0.355, 1.000);
      transition: all 0.7s 0.3s cubic-bezier(0.645, 0.045, 0.355, 1.000);
    }

    .loaded #loader {
      opacity: 0;
      -webkit-transition: all 0.3s ease-out;
      transition: all 0.3s ease-out;
    }

    .loaded #loader-wrapper {
      visibility: hidden;
      -webkit-transform: translateY(-100%);
      /* Chrome, Opera 15+, Safari 3.1+ */
      -ms-transform: translateY(-100%);
      /* IE 9 */
      transform: translateY(-100%);
      /* Firefox 16+, IE 10+, Opera */
      -webkit-transition: all 0.3s 1s ease-out;
      transition: all 0.3s 1s ease-out;
    }

    /* JavaScript Turned Off */

    .no-js #loader-wrapper {
      display: none;
    }

    .no-js h1 {
      color: #222222;
    }

    #loader-wrapper .load_title {
      font-family: 'Open Sans';
      color: #FFF;
      font-size: 19px;
      width: 100%;
      text-align: center;
      z-index: 9999999999999;
      position: absolute;
      top: 60%;
      opacity: 1;
      line-height: 30px;
    }

    #loader-wrapper .load_title span {
      font-weight: normal;
      font-style: italic;
      font-size: 13px;
      color: #FFF;
      opacity: 0.5;
    }
    .n_body1{
          position: fixed;
          top: 0;
          left: 0;
          width: 100%;
          height: 100%;
          z-index: 999999;
    }
</style>